﻿Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Xml
Imports System.IO
'--
Imports CrystalDecisions.CrystalReports
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.Windows.Forms
Imports CrystalDecisions.ReportSource

Public Class angDANFE
    Private myDataSet As DataSet
    Private myDanfe As String = ""
    Private PathBarra As String = strAppPath & "\temp\cod_barras.jpg", PathLogo As String = ""
    Private strMargens As String, myMargens As CrystalDecisions.Shared.PageMargins
    Private blnNoLogo As Boolean, blnDANFEExterno As Boolean
    Private strFldLogotipo As String = "logotipo1"
    Private strFldxNome As String = "xNome1"
    Private strFldxEndereco As String = "xEndereco1"
    ''' <summary>
    ''' Seta o caminho do arquivo XML para ser carregado
    ''' </summary>
    ''' <value></value>
    ''' <remarks>3.4.3.26</remarks>
    Public WriteOnly Property XMLFilePath()
        Set(ByVal value)
            blnNoLogo = True
            Call CarregaXML(value)
            Call IntegrarDataSet()
        End Set
    End Property
    ''' <summary>
    ''' Retorna o DataSet contendo os dados do XML já prontos para o Crystal
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property Dados() As DataSet
        Get
            Return myDataSet
        End Get
    End Property
    ''' <summary>
    ''' Retorna se DANFE contém logotipo do cliente
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property NoLogo() As Boolean
        Get
            Return blnNoLogo
        End Get
    End Property
    ''' <summary>
    ''' Retorna as configurações de margens do crystal
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property Margens() As CrystalDecisions.Shared.PageMargins
        Get
            Return myMargens
        End Get
    End Property
    ''' <summary>
    ''' Retorna caminho completo do arquivo do Crystal
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property CrystalFilePath() As String
        Get
            Return myCrystalFilePath
        End Get
    End Property
    ''' <summary>
    ''' Carrega as configurações para criação do relatório do Crystal
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub LoadConfig()
        Try
            Dim myConfig As New angNFeXMLGen
            Dim intMargens As Array
            With myConfig
                PathLogo = .GetConfig("nfe.danfe.logotipo")
                strMargens = .GetConfig("nfe.danfe.margens")
                myCrystalFilePath = strAppPath & "\danfes\" & .GetConfig("nfe.danfe.modelo")
                If PathLogo.Trim <> String.Empty Then
                    If File.Exists(PathLogo) = False Then
                        blnNoLogo = True
                    Else
                        blnNoLogo = False
                    End If
                End If
                If strMargens.Trim = String.Empty Or strMargens = "{ConfigNotFound}" Then
                    strMargens = "210x210x210x210"
                End If
                intMargens = Split(strMargens, "x")
                With myMargens
                    .topMargin = intMargens(0)
                    .bottomMargin = intMargens(1)
                    .leftMargin = intMargens(2)
                    .rightMargin = intMargens(3)
                End With
            End With
        Catch ex As Exception
            Throw New Exception("LoadConfig:Error:" & ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Integra os dados com o relatório
    ''' </summary>
    Public Sub IntegrarDataSet()
        Try
            Dim dsReport As DataSet = New dsDANFE()
            Dim dsTempReport As New DataSet()

            dsTempReport = CarregarDataSet()

            dsReport.Tables("dtProd").Merge(dsTempReport.Tables("prod"))
            dsReport.Tables("dtIde").Merge(dsTempReport.Tables("ide"))
            dsReport.Tables("dtEmit").Merge(dsTempReport.Tables("emit"))
            dsReport.Tables("dtDest").Merge(dsTempReport.Tables("dest"))
            dsReport.Tables("dtDup").Merge(dsTempReport.Tables("dup"))
            dsReport.Tables("dtTotal").Merge(dsTempReport.Tables("total"))
            dsReport.Tables("dtTransp").Merge(dsTempReport.Tables("transp"))
            dsReport.Tables("dtISSQN").Merge(dsTempReport.Tables("issqn"))
            dsReport.Tables("dtImages").Merge(ImageTable(PathBarra, PathLogo))

            myDataSet = dsReport
        Catch ex As Exception
            Throw New Exception("IntegrarDataSet:Error:" & ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Insere imagem dentro do DataSet para apresentação no relatório (FUNCIONAL)
    ''' </summary>
    Private Function ImageTable(ByVal ImageBarra As String, ByVal ImageLogo As String) As DataTable
        Try
            Dim data As New DataTable
            Dim row As DataRow

            data.TableName = "dtImages"
            data.Columns.Add("codBarra", System.Type.GetType("System.Byte[]"))
            data.Columns.Add("logotipo", System.Type.GetType("System.Byte[]"))
            data.Columns.Add("verProc").DefaultValue = "Powered by Angulo INC - RePro (v. " & strAppVersion & ") - http://www.anguloinc.com.br/repro"

            row = data.NewRow()
            '-- Codigo barras
            If File.Exists(ImageBarra) = True Then
                Dim fs As New FileStream(ImageBarra, FileMode.Open)
                Dim br As New BinaryReader(fs)
                row(0) = br.ReadBytes(br.BaseStream.Length)
                br = Nothing
                fs.Close()
                fs = Nothing
            End If
            '--
            If blnDANFEExterno = False Then
                If ImageLogo.Trim <> String.Empty Then
                    '-- Logotipo
                    ImageLogo = FolderPattern(ImageLogo)
                    If File.Exists(ImageLogo) = True Then
                        Dim fs1 As New FileStream(ImageLogo, FileMode.Open)
                        Dim br1 As New BinaryReader(fs1)
                        row(1) = br1.ReadBytes(br1.BaseStream.Length)
                        br1 = Nothing
                        fs1.Close()
                        fs1 = Nothing
                        blnNoLogo = False
                    End If
                End If
            Else
                blnNoLogo = blnDANFEExterno
            End If
            '--
            data.Rows.Add(row)

            Return data
        Catch ex As Exception
            Throw New Exception("ImageTable:Error:" & ex.Message)
            Return Nothing
        End Try
    End Function
    ''' <summary>
    ''' Carrega os dados para o relatório 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks> 3.4.3.26
    ''' 3.4.3.26 = correção ICMS60
    ''' </remarks>
    Private Function CarregarDataSet() As DataSet
        Try
            Dim myDataSet As New DataSet
            Dim myXml As New XmlDocument
            Dim myNFe As String = "", myTemp As String = ""
            Dim strRoot As String = "", strRootItem As String = "", strRootICMS As String = "", strRootIPI As String = ""
            Dim intProd, intCount As Integer
            Dim ICMS_ST As String, ICMS_CST As String = "", prodOrig, prodCST As String
            Dim chNFe, infProt, strDup As String
            Dim strVersao As String = ""
            '-- carregando o xml completo
            myXml.LoadXml(myDanfe)
            '-- verificando protocolo
            If myXml.GetElementsByTagName("nfeProc").Count = 0 Then
                Throw New Exception("XML da NFe não contém o protocolo de autorização!")
                Return Nothing
            End If
            '-- conferindo o protocolo
            If myXml.GetElementsByTagName("digVal").Count = 0 Then
                Throw New Exception("Protocolo da NFe não contém a TAG digVal!")
                Return Nothing
            End If
            If myXml.GetElementsByTagName("DigestValue").Item(0).InnerText <> myXml.GetElementsByTagName("digVal").Item(0).InnerText Then
                Throw New Exception("Digest Value da NFe não confere!")
                Return Nothing
            End If
            '-- Verifica se DANFE é de terceiros
            blnDANFEExterno = False
            If myXml.GetElementsByTagName("CNPJ").Item(0).InnerText <> strAppRegDocto Then
                blnDANFEExterno = True ' Se for não tem logo
            End If
            '--
            With myDataSet
                '-- gerando codigo de barras
                chNFe = myXml.SelectNodes("/nfeProc/protNFe/infProt/chNFe").Item(0).InnerText
                infProt = myXml.SelectNodes("/nfeProc/protNFe/infProt/nProt").Item(0).InnerText
                infProt &= " - " & Format(CDate(myXml.SelectNodes("/nfeProc/protNFe/infProt/dhRecbto").Item(0).InnerText.Replace("T", " ")), "dd/MM/yyyy HH:mm:ss")
                Call GerarBarras(chNFe)
                '-- verão do layout da nota
                strVersao = myXml.GetElementsByTagName("infNFe").Item(0).Attributes("versao").Value
                '-- pegando somente os dados da NFe
                myNFe = myXml.GetElementsByTagName("infNFe").Item(0).OuterXml
                '-- carregado somente os dados do danfe
                myXml.LoadXml(myNFe)
                '-- CRIANDO TABELAS
                .Tables.Add("prod") '-- dtProd
                .Tables("prod").Columns.Add("nItem").DefaultValue = ""
                .Tables("prod").Columns.Add("cProd").DefaultValue = ""
                .Tables("prod").Columns.Add("xProd").DefaultValue = ""
                .Tables("prod").Columns.Add("NCM").DefaultValue = ""
                .Tables("prod").Columns.Add("CFOP").DefaultValue = ""
                .Tables("prod").Columns.Add("uCom").DefaultValue = ""
                .Tables("prod").Columns.Add("qCom").DefaultValue = ""
                .Tables("prod").Columns.Add("vUnCom").DefaultValue = ""
                .Tables("prod").Columns.Add("vDesc").DefaultValue = ""
                .Tables("prod").Columns.Add("vProd").DefaultValue = ""
                .Tables("prod").Columns.Add("orig").DefaultValue = ""
                .Tables("prod").Columns.Add("vBC").DefaultValue = ""
                .Tables("prod").Columns.Add("vBCST").DefaultValue = ""
                .Tables("prod").Columns.Add("pICMS").DefaultValue = ""
                .Tables("prod").Columns.Add("vICMS").DefaultValue = ""
                .Tables("prod").Columns.Add("vICMSST").DefaultValue = ""
                .Tables("prod").Columns.Add("vIPI").DefaultValue = ""
                .Tables("prod").Columns.Add("pIPI").DefaultValue = ""
                .Tables("prod").Columns.Add("infAdProd").DefaultValue = ""
                .Tables.Add("ide") '-- dtIde
                .Tables("ide").Columns.Add("chNFe").DefaultValue = ""
                .Tables("ide").Columns.Add("natOp").DefaultValue = ""
                .Tables("ide").Columns.Add("infProt").DefaultValue = ""
                .Tables("ide").Columns.Add("dEmi").DefaultValue = ""
                .Tables("ide").Columns.Add("dSaiEnt").DefaultValue = ""
                .Tables("ide").Columns.Add("hSaiEnt").DefaultValue = ""
                .Tables("ide").Columns.Add("nNF").DefaultValue = ""
                .Tables("ide").Columns.Add("serie").DefaultValue = ""
                .Tables("ide").Columns.Add("tpNF").DefaultValue = ""
                .Tables("ide").Columns.Add("infAdic").DefaultValue = ""
                .Tables("ide").Columns.Add("tpAmb").DefaultValue = ""
                .Tables.Add("emit") '-- dtEmit
                .Tables("emit").Columns.Add("CNPJ").DefaultValue = ""
                .Tables("emit").Columns.Add("IE").DefaultValue = ""
                .Tables("emit").Columns.Add("IEST").DefaultValue = ""
                .Tables("emit").Columns.Add("xNome").DefaultValue = ""
                .Tables("emit").Columns.Add("xEndereco").DefaultValue = ""
                .Tables.Add("dest") '-- dtDest
                .Tables("dest").Columns.Add("CNPJ").DefaultValue = ""
                .Tables("dest").Columns.Add("IE").DefaultValue = ""
                .Tables("dest").Columns.Add("xNome").DefaultValue = ""
                .Tables("dest").Columns.Add("xLgr").DefaultValue = ""
                .Tables("dest").Columns.Add("xBairro").DefaultValue = ""
                .Tables("dest").Columns.Add("xMun").DefaultValue = ""
                .Tables("dest").Columns.Add("CEP").DefaultValue = ""
                .Tables("dest").Columns.Add("fone").DefaultValue = ""
                .Tables("dest").Columns.Add("UF").DefaultValue = ""
                .Tables.Add("dup") '-- dtDup
                .Tables("dup").Columns.Add("nDup1").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc1").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup1").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup2").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc2").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup2").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup3").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc3").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup3").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup4").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc4").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup4").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup5").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc5").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup5").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup6").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc6").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup6").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup7").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc7").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup7").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup8").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc8").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup8").DefaultValue = ""
                .Tables("dup").Columns.Add("nDup9").DefaultValue = ""
                .Tables("dup").Columns.Add("dVenc9").DefaultValue = ""
                .Tables("dup").Columns.Add("vDup9").DefaultValue = ""
                .Tables.Add("total") '-- dtTotal
                .Tables("total").Columns.Add("vBC").DefaultValue = ""
                .Tables("total").Columns.Add("vICMS").DefaultValue = ""
                .Tables("total").Columns.Add("vBCST").DefaultValue = ""
                .Tables("total").Columns.Add("vST").DefaultValue = ""
                .Tables("total").Columns.Add("vProd").DefaultValue = ""
                .Tables("total").Columns.Add("vFrete").DefaultValue = ""
                .Tables("total").Columns.Add("vSeg").DefaultValue = ""
                .Tables("total").Columns.Add("vDesc").DefaultValue = ""
                .Tables("total").Columns.Add("vOutro").DefaultValue = ""
                .Tables("total").Columns.Add("vIPI").DefaultValue = ""
                .Tables("total").Columns.Add("vNF").DefaultValue = ""
                .Tables.Add("transp") '-- dtTransp
                .Tables("transp").Columns.Add("modFrete").DefaultValue = ""
                .Tables("transp").Columns.Add("CNPJ").DefaultValue = ""
                .Tables("transp").Columns.Add("IE").DefaultValue = ""
                .Tables("transp").Columns.Add("xNome").DefaultValue = ""
                .Tables("transp").Columns.Add("xEnder").DefaultValue = ""
                .Tables("transp").Columns.Add("xMun").DefaultValue = ""
                .Tables("transp").Columns.Add("UF").DefaultValue = ""
                .Tables("transp").Columns.Add("qVol").DefaultValue = ""
                .Tables("transp").Columns.Add("esp").DefaultValue = ""
                .Tables("transp").Columns.Add("marca").DefaultValue = ""
                .Tables("transp").Columns.Add("pesoL").DefaultValue = ""
                .Tables("transp").Columns.Add("pesoB").DefaultValue = ""
                .Tables("transp").Columns.Add("nVol").DefaultValue = ""
                .Tables("transp").Columns.Add("RNTC").DefaultValue = ""
                .Tables("transp").Columns.Add("placa").DefaultValue = ""
                .Tables("transp").Columns.Add("veicUF").DefaultValue = ""
                .Tables.Add("issqn") '-- dtISSQN
                .Tables("issqn").Columns.Add("IM").DefaultValue = ""
                .Tables("issqn").Columns.Add("vServ").DefaultValue = ""
                .Tables("issqn").Columns.Add("vBC").DefaultValue = ""
                .Tables("issqn").Columns.Add("vISS").DefaultValue = ""
                '--
                '-- PREENCHENDO COM OS DADOS
                '--
                '-- dtIde
                strRoot = "/infNFe/ide"
                .Tables("ide").Rows.Add()
                .Tables("ide").Rows(0).Item("chNFe") = Mask(chNFe, "9999 9999 9999 9999 9999 9999 9999 9999 9999 9999 9999")
                .Tables("ide").Rows(0).Item("natOp") = myXml.SelectNodes(strRoot & "/natOp").Item(0).InnerText
                .Tables("ide").Rows(0).Item("infProt") = infProt
                .Tables("ide").Rows(0).Item("dEmi") = Format(CDate(myXml.SelectNodes(strRoot & "/dEmi").Item(0).InnerText), "dd/MM/yyyy")
                If myXml.SelectNodes(strRoot & "/dSaiEnt").Count > 0 Then
                    .Tables("ide").Rows(0).Item("dSaiEnt") = Format(CDate(myXml.SelectNodes(strRoot & "/dSaiEnt").Item(0).InnerText), "dd/MM/yyyy")
                End If
                If myXml.SelectNodes(strRoot & "/hSaiEnt").Count > 0 Then
                    .Tables("ide").Rows(0).Item("hSaiEnt") = Format(CDate(myXml.SelectNodes(strRoot & "/hSaiEnt").Item(0).InnerText), "HH:mm:ss")
                End If
                .Tables("ide").Rows(0).Item("nNF") = "Nº " & Mask(myXml.SelectNodes(strRoot & "/nNF").Item(0).InnerText, "000.000.000")
                .Tables("ide").Rows(0).Item("serie") = "SÉRIE " & Mask(myXml.SelectNodes(strRoot & "/serie").Item(0).InnerText, "000")
                .Tables("ide").Rows(0).Item("tpNF") = myXml.SelectNodes(strRoot & "/tpNF").Item(0).InnerText
                .Tables("ide").Rows(0).Item("tpAmb") = myXml.SelectNodes(strRoot & "/tpAmb").Item(0).InnerText
                If myXml.SelectNodes("/infNFe/infAdic/infAdFisco").Count > 0 Then
                    myTemp = myXml.SelectNodes("/infNFe/infAdic/infAdFisco").Item(0).InnerText & vbCrLf
                End If
                If myXml.SelectNodes("/infNFe/infAdic/infCpl").Count > 0 Then
                    myTemp &= myXml.SelectNodes("/infNFe/infAdic/infCpl").Item(0).InnerText
                End If
                .Tables("ide").Rows(0).Item("infAdic") = myTemp
                '-- dtEmit
                strRoot = "/infNFe/emit/enderEmit"
                myTemp = myXml.SelectNodes(strRoot & "/xLgr").Item(0).InnerText & ", "
                myTemp &= myXml.SelectNodes(strRoot & "/nro").Item(0).InnerText & vbCrLf
                myTemp &= myXml.SelectNodes(strRoot & "/xBairro").Item(0).InnerText & vbCrLf
                myTemp &= myXml.SelectNodes(strRoot & "/xMun").Item(0).InnerText & " - "
                myTemp &= myXml.SelectNodes(strRoot & "/UF").Item(0).InnerText & vbCrLf
                myTemp &= "CEP: " & Mask(myXml.SelectNodes(strRoot & "/CEP").Item(0).InnerText, "00000-000") & vbCrLf
                myTemp &= "FONE: " & Mask(myXml.SelectNodes(strRoot & "/fone").Item(0).InnerText, "00 0000-0000")
                strRoot = "/infNFe/emit"
                .Tables("emit").Rows.Add()
                .Tables("emit").Rows(0).Item("CNPJ") = Mask(myXml.SelectNodes(strRoot & "/CNPJ").Item(0).InnerText, "00.000.000/0000-00")
                If IsNumeric(myXml.SelectNodes(strRoot & "/IE").Item(0).InnerText) = True Then
                    .Tables("emit").Rows(0).Item("IE") = Mask(myXml.SelectNodes(strRoot & "/IE").Item(0).InnerText, "000.000.000.000")
                Else
                    .Tables("emit").Rows(0).Item("IE") = myXml.SelectNodes(strRoot & "/IE").Item(0).InnerText
                End If

                If myXml.SelectNodes(strRoot & "/IEST").Count > 0 Then
                    .Tables("emit").Rows(0).Item("IEST") = myXml.SelectNodes(strRoot & "/IEST").Item(0).InnerText
                End If
                .Tables("emit").Rows(0).Item("xNome") = myXml.SelectNodes(strRoot & "/xNome").Item(0).InnerText
                .Tables("emit").Rows(0).Item("xEndereco") = myTemp
                '-- dtDest
                strRoot = "/infNFe/dest"
                .Tables("dest").Rows.Add()
                If myXml.SelectNodes(strRoot & "/CNPJ").Count > 0 Then
                    .Tables("dest").Rows(0).Item("CNPJ") = Mask(myXml.SelectNodes(strRoot & "/CNPJ").Item(0).InnerText, "00.000.000/0000-00")
                End If
                If myXml.SelectNodes(strRoot & "/CPF").Count > 0 Then
                    .Tables("dest").Rows(0).Item("CNPJ") = Mask(myXml.SelectNodes(strRoot & "/CPF").Item(0).InnerText, "000.000.000-00")
                End If
                .Tables("dest").Rows(0).Item("IE") = myXml.SelectNodes(strRoot & "/IE").Item(0).InnerText
                '--
                .Tables("dest").Rows(0).Item("xNome") = myXml.SelectNodes(strRoot & "/xNome").Item(0).InnerText
                strRoot = "/infNFe/dest/enderDest"
                myTemp = myXml.SelectNodes(strRoot & "/xLgr").Item(0).InnerText & ", "
                myTemp &= myXml.SelectNodes(strRoot & "/nro").Item(0).InnerText & vbCrLf
                .Tables("dest").Rows(0).Item("xLgr") = myTemp
                .Tables("dest").Rows(0).Item("xBairro") = myXml.SelectNodes(strRoot & "/xBairro").Item(0).InnerText
                .Tables("dest").Rows(0).Item("xMun") = myXml.SelectNodes(strRoot & "/xMun").Item(0).InnerText
                If myXml.SelectNodes(strRoot & "/CEP").Count > 0 Then
                    .Tables("dest").Rows(0).Item("CEP") = Mask(myXml.SelectNodes(strRoot & "/CEP").Item(0).InnerText, "00000-000")
                End If
                If myXml.SelectNodes(strRoot & "/fone").Count > 0 Then
                    .Tables("dest").Rows(0).Item("fone") = Mask(myXml.SelectNodes(strRoot & "/fone").Item(0).InnerText, "00 0000-0000")
                End If
                .Tables("dest").Rows(0).Item("UF") = myXml.SelectNodes(strRoot & "/UF").Item(0).InnerText
                '-- formatação IE precisa UF
                .Tables("dest").Rows(0).Item("IE") = RetornaIEMask(.Tables("dest").Rows(0).Item("UF"), .Tables("dest").Rows(0).Item("IE"))
                '-- dtDup
                strRoot = "/infNFe"
                If myXml.SelectNodes(strRoot & "/cobr").Count > 0 Then
                    strRoot = "/infNFe/cobr"
                    If myXml.SelectNodes(strRoot & "/dup").Count > 0 Then
                        .Tables("dup").Rows.Add()
                        For intCount = 0 To myXml.SelectNodes(strRoot & "/dup").Count - 1
                            strRoot = "/infNFe/cobr/dup"
                            If myXml.SelectNodes(strRoot & "/nDup").Count > 0 Then
                                strDup = "nDup" & intCount + 1
                                .Tables("dup").Rows(0).Item(strDup) = myXml.SelectNodes(strRoot & "/nDup").Item(intCount).InnerText
                            End If
                            If myXml.SelectNodes(strRoot & "/dVenc").Count > 0 Then
                                strDup = "dVenc" & intCount + 1
                                .Tables("dup").Rows(0).Item(strDup) = Format(CDate(myXml.SelectNodes(strRoot & "/dVenc").Item(intCount).InnerText), "dd/MM/yyyy")
                            End If
                            If myXml.SelectNodes(strRoot & "/vDup").Count > 0 Then
                                strDup = "vDup" & intCount + 1
                                .Tables("dup").Rows(0).Item(strDup) = TrataValor(myXml.SelectNodes(strRoot & "/vDup").Item(intCount).InnerText)
                            End If
                        Next
                    End If
                End If
                '-- dtTotal
                strRoot = "/infNFe/total/ICMSTot"
                .Tables("total").Rows.Add()
                .Tables("total").Rows(0).Item("vBC") = TrataValor(myXml.SelectNodes(strRoot & "/vBC").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vICMS") = TrataValor(myXml.SelectNodes(strRoot & "/vICMS").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vBCST") = TrataValor(myXml.SelectNodes(strRoot & "/vBCST").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vST") = TrataValor(myXml.SelectNodes(strRoot & "/vST").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vProd") = TrataValor(myXml.SelectNodes(strRoot & "/vProd").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vFrete") = TrataValor(myXml.SelectNodes(strRoot & "/vFrete").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vSeg") = TrataValor(myXml.SelectNodes(strRoot & "/vSeg").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vDesc") = TrataValor(myXml.SelectNodes(strRoot & "/vDesc").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vOutro") = TrataValor(myXml.SelectNodes(strRoot & "/vOutro").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vIPI") = TrataValor(myXml.SelectNodes(strRoot & "/vIPI").Item(0).InnerText)
                .Tables("total").Rows(0).Item("vNF") = TrataValor(myXml.SelectNodes(strRoot & "/vNF").Item(0).InnerText)
                '-- dtTransp
                strRoot = "/infNFe/transp"
                .Tables("transp").Rows.Add()
                .Tables("transp").Rows(0).Item("modFrete") = myXml.SelectNodes(strRoot & "/modFrete").Item(0).InnerText
                If myXml.SelectNodes(strRoot & "/transporta").Count > 0 Then
                    strRoot = "/infNFe/transp/transporta"
                    If myXml.SelectNodes(strRoot & "/CNPJ").Count > 0 Then
                        .Tables("transp").Rows(0).Item("CNPJ") = Mask(myXml.SelectNodes(strRoot & "/CNPJ").Item(0).InnerText, "00.000.000/0000-00")
                    End If
                    If myXml.SelectNodes(strRoot & "/CPF").Count > 0 Then
                        .Tables("transp").Rows(0).Item("CNPJ") = Mask(myXml.SelectNodes(strRoot & "/CPF").Item(0).InnerText, "000.000.000-00")
                    End If
                    If myXml.SelectNodes(strRoot & "/IE").Count > 0 Then
                        .Tables("transp").Rows(0).Item("IE") = myXml.SelectNodes(strRoot & "/IE").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/xNome").Count > 0 Then
                        .Tables("transp").Rows(0).Item("xNome") = myXml.SelectNodes(strRoot & "/xNome").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/xEnder").Count > 0 Then
                        .Tables("transp").Rows(0).Item("xEnder") = myXml.SelectNodes(strRoot & "/xEnder").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/xMun").Count > 0 Then
                        .Tables("transp").Rows(0).Item("xMun") = myXml.SelectNodes(strRoot & "/xMun").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/UF").Count > 0 Then
                        .Tables("transp").Rows(0).Item("UF") = myXml.SelectNodes(strRoot & "/UF").Item(0).InnerText
                        .Tables("transp").Rows(0).Item("IE") = RetornaIEMask(.Tables("transp").Rows(0).Item("UF"), .Tables("transp").Rows(0).Item("IE"))
                    End If
                End If
                strRoot = "/infNFe/transp"
                If myXml.SelectNodes(strRoot & "/vol").Count > 0 Then
                    strRoot = "/infNFe/transp/vol"
                    If myXml.SelectNodes(strRoot & "/qVol").Count > 0 Then
                        .Tables("transp").Rows(0).Item("qVol") = myXml.SelectNodes(strRoot & "/qVol").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/esp").Count > 0 Then
                        .Tables("transp").Rows(0).Item("esp") = myXml.SelectNodes(strRoot & "/esp").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/marca").Count > 0 Then
                        .Tables("transp").Rows(0).Item("marca") = myXml.SelectNodes(strRoot & "/marca").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/pesoL").Count > 0 Then
                        .Tables("transp").Rows(0).Item("pesoL") = TrataValor(myXml.SelectNodes(strRoot & "/pesoL").Item(0).InnerText)
                    End If
                    If myXml.SelectNodes(strRoot & "/pesoB").Count > 0 Then
                        .Tables("transp").Rows(0).Item("pesoB") = TrataValor(myXml.SelectNodes(strRoot & "/pesoB").Item(0).InnerText)
                    End If
                    If myXml.SelectNodes(strRoot & "/nVol").Count > 0 Then
                        .Tables("transp").Rows(0).Item("nVol") = myXml.SelectNodes(strRoot & "/nVol").Item(0).InnerText
                    End If
                End If
                strRoot = "/infNFe/transp"
                If myXml.SelectNodes(strRoot & "/veicTransp").Count > 0 Then
                    strRoot = "/infNFe/transp/veicTransp"
                    .Tables("transp").Rows(0).Item("placa") = myXml.SelectNodes(strRoot & "/placa").Item(0).InnerText
                    .Tables("transp").Rows(0).Item("veicUF") = myXml.SelectNodes(strRoot & "/UF").Item(0).InnerText
                    If myXml.SelectNodes(strRoot & "/RNTC").Count > 0 Then
                        .Tables("transp").Rows(0).Item("RNTC") = myXml.SelectNodes(strRoot & "/RNTC").Item(0).InnerText
                    End If
                End If
                If myXml.SelectNodes(strRoot & "/reboque").Count > 0 Then
                    strRoot = "/infNFe/transp/reboque"
                    .Tables("transp").Rows(0).Item("placa") = myXml.SelectNodes(strRoot & "/placa").Item(0).InnerText
                    .Tables("transp").Rows(0).Item("veicUF") = myXml.SelectNodes(strRoot & "/UF").Item(0).InnerText
                    If myXml.SelectNodes(strRoot & "/RNTC").Count > 0 Then
                        .Tables("transp").Rows(0).Item("RNTC") = myXml.SelectNodes(strRoot & "/RNTC").Item(0).InnerText
                    End If
                End If
                '-- dtProd
                For intProd = 0 To myXml.GetElementsByTagName("det").Count - 1
                    strRootItem = "/infNFe/det[@nItem=" & intProd + 1 & "]/prod"
                    'Debug.WriteLine(myXml.SelectNodes(strRootItem & "/xProd").Item(0).InnerText)
                    .Tables("prod").Rows.Add()
                    .Tables("prod").Rows(intProd).Item("nItem") = Format(intProd, "000").ToString
                    .Tables("prod").Rows(intProd).Item("cProd") = myXml.SelectNodes(strRootItem & "/cProd").Item(0).InnerText
                    .Tables("prod").Rows(intProd).Item("xProd") = myXml.SelectNodes(strRootItem & "/xProd").Item(0).InnerText
                    If myXml.SelectNodes(strRootItem & "/NCM").Count > 0 Then
                        .Tables("prod").Rows(intProd).Item("NCM") = Mask(myXml.SelectNodes(strRootItem & "/NCM").Item(0).InnerText, "9999.99.99")
                    End If
                    .Tables("prod").Rows(intProd).Item("CFOP") = myXml.SelectNodes(strRootItem & "/CFOP").Item(0).InnerText
                    .Tables("prod").Rows(intProd).Item("uCom") = myXml.SelectNodes(strRootItem & "/uCom").Item(0).InnerText
                    .Tables("prod").Rows(intProd).Item("qCom") = TrataValor(myXml.SelectNodes(strRootItem & "/qCom").Item(0).InnerText)
                    .Tables("prod").Rows(intProd).Item("vUnCom") = TrataValor(myXml.SelectNodes(strRootItem & "/vUnCom").Item(0).InnerText)
                    '.Tables("prod").Rows(intProd).Item("vDesc") = myXml.GetElementsByTagName("vDesc").Item(intProd).InnerText
                    .Tables("prod").Rows(intProd).Item("vProd") = TrataValor(myXml.SelectNodes(strRootItem & "/vProd").Item(0).InnerText)

                    strRootItem = "/infNFe/det[@nItem=" & intProd + 1 & "]"
                    If myXml.SelectNodes(strRootItem & "/infAdProd").Count > 0 Then
                        .Tables("prod").Rows(intProd).Item("infAdProd") = myXml.SelectNodes(strRootItem & "/infAdProd").Item(0).InnerText
                        .Tables("prod").Rows(intProd).Item("xProd") &= vbCrLf & myXml.SelectNodes(strRootItem & "/infAdProd").Item(0).InnerText
                    End If

                    If myXml.SelectNodes(strRootItem & "/imposto/ICMS").Count > 0 Then '-- tem ICMS
                        ICMS_ST = myXml.SelectNodes(strRootItem & "/imposto/ICMS").Item(0).ChildNodes.Item(0).Name
                        strRootICMS = strRootItem & "/imposto/ICMS/" & ICMS_ST
                        '--
                        prodOrig = myXml.SelectNodes(strRootICMS & "/orig").Item(0).InnerText
                        Select Case ICMS_ST
                            Case "ICMS00", "ICMS20"
                                '00 – Tributada(integralmente)
                                '20 - Com redução de base de cálculo
                                prodCST = myXml.SelectNodes(strRootICMS & "/CST").Item(0).InnerText
                                .Tables("prod").Rows(intProd).Item("vBC") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBC").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMS").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("pICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/pICMS").Item(0).InnerText)
                            Case "ICMS51"
                                '51 - Diferimento
                                'A exigência do preenchimento das informações do ICMS diferido fica à critério de cada UF
                                prodCST = myXml.SelectNodes(strRootICMS & "/CST").Item(0).InnerText
                                If myXml.SelectNodes(strRootICMS & "/vBC").Count > 0 Then
                                    .Tables("prod").Rows(intProd).Item("vBC") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBC").Item(0).InnerText)
                                    .Tables("prod").Rows(intProd).Item("vICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMS").Item(0).InnerText)
                                    .Tables("prod").Rows(intProd).Item("pICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/pICMS").Item(0).InnerText)
                                End If
                            Case "ICMS10", "ICMS70", "ICMS90"
                                '10 - Tributada e com cobrança do ICMS por substituição tributária
                                '70 - Com redução de base de cálculo e cobrança do ICMS por substituição tributária ICMS por substituição tributária
                                '90 - Outros
                                prodCST = myXml.SelectNodes(strRootICMS & "/CST").Item(0).InnerText
                                .Tables("prod").Rows(intProd).Item("vBC") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBC").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vBCST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBCST").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("pICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/pICMS").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMS").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vICMSST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMSST").Item(0).InnerText)
                            Case "ICMS30"
                                '30 - Isenta ou não tributada e com cobrança do ICMS por substituição tributária
                                prodCST = myXml.SelectNodes(strRootICMS & "/CST").Item(0).InnerText
                                .Tables("prod").Rows(intProd).Item("vBCST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBCST").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("pICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/pICMS").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vICMSST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMSST").Item(0).InnerText)
                            Case "ICMS60"
                                '60 - ICMS cobrado anteriormente por substituição tributária
                                prodCST = myXml.SelectNodes(strRootICMS & "/CST").Item(0).InnerText
                                Select Case strVersao
                                    Case "1.00"
                                        .Tables("prod").Rows(intProd).Item("vBCST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBCST").Item(0).InnerText)
                                        .Tables("prod").Rows(intProd).Item("vICMSST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMSST").Item(0).InnerText)
                                    Case Else
                                        .Tables("prod").Rows(intProd).Item("vBCST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBCSTRet").Item(0).InnerText)
                                        .Tables("prod").Rows(intProd).Item("vICMSST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMSSTRet").Item(0).InnerText)
                                End Select
                            Case "ICMS40", "ICMS41", "ICMS50"
                                '40 - Isenta
                                '41 - Não tributada
                                '50 - Suspensão
                                prodCST = myXml.SelectNodes(strRootICMS & "/CST").Item(0).InnerText
                            Case "ICMSSN101", "ICMSSN102", "ICMSSN103", "ICMSSN300", "ICMSSN400"
                                '101- Tributada pelo Simples Nacional com permissão de crédito.
                                '102 - Tributada pelo Simples Nacional sem permissão de crédito.
                                '103 – Isenção do ICMS no Simples Nacional para faixa de receita bruta.
                                '300 – Imune.
                                '400 – Não tributada pelo Simples Nacional
                                prodCST = myXml.SelectNodes(strRootICMS & "/CSOSN").Item(0).InnerText
                            Case "ICMSSN201", "ICMSSN202", "ICMSSN203"
                                '201 - Tributada pelo Simples Nacional com permissão de crédito e com cobrança do ICMS por Substituição Tributária
                                '202 - Tributada pelo Simples Nacional sem permissão de crédito e com cobrança do ICMS por Substituição Tributária
                                '203 - Isenção do ICMS nos Simples Nacional para faixa de receita bruta e com cobrança do ICMS por Substituição Tributária
                                prodCST = myXml.SelectNodes(strRootICMS & "/CSOSN").Item(0).InnerText
                                .Tables("prod").Rows(intProd).Item("vBCST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBCST").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("pICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/pICMSST").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vICMSST") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMSST").Item(0).InnerText)
                            Case "ICMSSN500"
                                '500 – ICMS cobrado anteriormente por substituição tributária (substituído) ou por antecipação
                                prodCST = myXml.SelectNodes(strRootICMS & "/CSOSN").Item(0).InnerText
                            Case "ICMSSN900"
                                '900 - Outros
                                prodCST = myXml.SelectNodes(strRootICMS & "/CSOSN").Item(0).InnerText
                                .Tables("prod").Rows(intProd).Item("vBC") = TrataValor(myXml.SelectNodes(strRootICMS & "/vBC").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("vICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/vICMS").Item(0).InnerText)
                                .Tables("prod").Rows(intProd).Item("pICMS") = TrataValor(myXml.SelectNodes(strRootICMS & "/pICMS").Item(0).InnerText)
                            Case Else
                                prodCST = "??"
                        End Select
                        '-- 
                        .Tables("prod").Rows(intProd).Item("orig") = prodOrig & prodCST
                    End If
                    If myXml.SelectNodes(strRootItem & "/imposto/IPI").Count > 0 Then '-- tem IPI
                        strRootIPI = strRootItem & "/imposto/IPI/IPITrib"
                        If myXml.SelectNodes(strRootIPI).Count > 0 Then '-- Tributado
                            .Tables("prod").Rows(intProd).Item("vIPI") = TrataValor(myXml.SelectNodes(strRootIPI & "/vIPI").Item(0).InnerText)
                            .Tables("prod").Rows(intProd).Item("pIPI") = TrataValor(myXml.SelectNodes(strRootIPI & "/pIPI").Item(0).InnerText)
                        Else '-- isento
                            .Tables("prod").Rows(intProd).Item("vIPI") = ""
                            .Tables("prod").Rows(intProd).Item("pIPI") = ""
                        End If
                    End If
                Next
                '-- dtISSQN
                strRoot = "/infNFe/total/ISSQNtot"
                If myXml.SelectNodes(strRoot).Count > 0 Then
                    .Tables("issqn").Rows.Add()
                    If myXml.SelectNodes("/infNFe/emit/IM").Count > 0 Then '-- verifica se tem Inscrição Municipal (C-19)
                        .Tables("issqn").Rows(0).Item("IM") = myXml.SelectNodes(strRoot & "/IM").Item(0).InnerText
                    End If
                    If myXml.SelectNodes(strRoot & "/vServ").Count > 0 Then
                        .Tables("issqn").Rows(0).Item("vServ") = TrataValor(myXml.SelectNodes(strRoot & "/vServ").Item(0).InnerText)
                    End If
                    If myXml.SelectNodes(strRoot & "/vBC").Count > 0 Then
                        .Tables("issqn").Rows(0).Item("vBC") = TrataValor(myXml.SelectNodes(strRoot & "/vBC").Item(0).InnerText)
                    End If
                    If myXml.SelectNodes(strRoot & "/vISS").Count > 0 Then
                        .Tables("issqn").Rows(0).Item("vISS") = TrataValor(myXml.SelectNodes(strRoot & "/vISS").Item(0).InnerText)
                    End If
                End If
            End With

            Return myDataSet
        Catch ex As Exception
            Throw New Exception("CarregarDataSet:Error:" & ex.Message)
            Return Nothing
        End Try
    End Function
    ''' <summary>
    ''' Rotina de retorna a Inscrição Estadual já com a mascara
    ''' </summary>
    ''' <param name="UF">UF</param>
    ''' <param name="IE">Número da Inscrição Estadual</param>
    ''' <returns>String já formatada</returns>
    ''' <remarks>3.4.3.25</remarks>
    Private Function RetornaIEMask(ByVal UF As String, ByVal IE As String) As String
        If IE.ToUpper = "ISENTO" Then
            Return IE
        End If
        If IsEmpty(IE) Then
            Return IE
        End If
        '--MOD 
        Select Case UF.ToUpper
            Case "ES"
                Return Mask(IE, "000.000.00-0")
            Case "GO", "MS", "MT", "PB", "RN"
                Return Mask(IE, "00.000.000-0")
            Case "PR"
                Return Mask(IE, "00000000-00")
            Case "SP"
                Return Mask(IE, "000.000.000.000")
            Case "MG"
                Return Mask(IE, "000000000.00-00")
            Case "RS"
                Return Mask(IE, "000/0000000")
            Case Else
                Return IE
        End Select
    End Function
    ''' <summary>
    ''' Carrega o XML para o DANFE num string
    ''' </summary>
    Private Sub CarregaXML(ByVal FileName As String)
        Try
            myDanfe = File.ReadAllText(FileName)
            myDanfe = Replace(myDanfe, " xmlns=""http://www.portalfiscal.inf.br/nfe""", "")
            '-- limpando o dataset
            myDataSet = Nothing
        Catch ex As Exception
            Throw New Exception("CarregaXML:Error:" & ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Gerra a imagem temporária com o código de barras
    ''' </summary>
    Private Function GerarBarras(ByVal strCodBarras As String) As Boolean
        Try
            If strCodBarras.Trim = String.Empty Then Exit Try
            Dim Barcode As New BarcodeLib.Barcode(strCodBarras, BarcodeLib.TYPE.CODE128C)
            'PictureBox1.Image = Barcode.Encode(BarcodeLib.TYPE.CODE128C, strCodBarras, 300, 150)
            'PictureBox1.Image = Barcode.Encode(BarcodeLib.TYPE.CODE128C, strCodBarras, 285, 35)
            'PictureBox1.Visible = True

            Barcode.Encode(BarcodeLib.TYPE.CODE128C, strCodBarras, 285, 35)
            Barcode.SaveImage(strAppPath & "\temp\cod_barras.jpg", BarcodeLib.SaveTypes.JPG)
            Return True
        Catch ex As Exception
            Throw New Exception("GerarBarras:Error:" & ex.Message)
            Return False
        End Try
    End Function
    ''' <summary>
    ''' Salva o relatório em PDF automaticamente
    ''' </summary>
    ''' <param name="ProtFileName">Caminho do protocolo XML</param>
    ''' <param name="PDFFileName">Nome do arquivo PDF para salvamento.</param>
    ''' <returns>Retorna caminho completo do arquivo PDF salvo.</returns>
    ''' <remarks>3.4.3.26</remarks>
    Public Function SavePDF(ByVal ProtFileName As String, ByVal PDFFileName As String) As String
        Try
            Dim myCR As New ReportDocument
            Dim CrExportOptions As New CrystalDecisions.Shared.ExportOptions
            Dim CrDiskFileDestinationOptions As New CrystalDecisions.Shared.DiskFileDestinationOptions()
            Dim CrFormatTypeOptions As New CrystalDecisions.Shared.PdfRtfWordFormatOptions()
            Dim myDataset As New angDANFE
            Dim strPDFPath As String = strAppPath & "\temp\" & PDFFileName

            myDataset.LoadConfig()
            myDataset.XMLFilePath = ProtFileName
            myCR.Load(myDataset.CrystalFilePath)

            CrDiskFileDestinationOptions.DiskFileName = strPDFPath
            'CrFormatTypeOptions.FirstPageNumber = 1 ' Start Page in the Report
            'CrFormatTypeOptions.LastPageNumber = 3 ' End Page in the Report
            'CrFormatTypeOptions.UsePageRange = True
            CrExportOptions = myCR.ExportOptions
            '-- Opções de exportação
            With CrExportOptions
                .ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile 'Set the destination to a disk file
                .ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat 'Set the format to PDF
                .DestinationOptions = CrDiskFileDestinationOptions 'Set the destination options to DiskFileDestinationOptions object
                .FormatOptions = CrFormatTypeOptions
            End With
            '-- carregando o relatório
            With myCR
                .SetDataSource(myDataset.Dados)
                .PrintOptions.ApplyPageMargins(myDataset.Margens)
                If myDataset.NoLogo = True Then
                    Call UpdateReportObjectProperties(myCR, strFldLogotipo, 0, 0, 0, 0, False)
                    Call UpdateReportObjectProperties(myCR, strFldxNome, 0, 120, 0, 3480)
                    Call UpdateReportObjectProperties(myCR, strFldxEndereco, 0, 120, 0, 0)
                End If
                .Export()
                .Dispose()
            End With
            Return strPDFPath
        Catch ex As Exception
            Throw New Exception("SavePDF:" & ex.Message)
        End Try
    End Function
    ''' <summary>
    ''' Imprime o relatório diretamente na impressora padrão 
    ''' </summary>
    ''' <param name="strFilePath">Nome do arquivo XML a ser impresso do DANFE</param>
    ''' <remarks>3.4.3.26</remarks>
    Public Sub PrintRelDirect(ByVal strFilePath As String)
        Try
            Dim PrinterName As String = angNFeXMLGen.GetConfig("nfe.danfe.impressora")
            Dim myDataset As New angDANFE
            Dim myCR As New ReportDocument
            '--
            myDataset.LoadConfig()
            myDataset.XMLFilePath = strFilePath
            '--
            With myCR
                .Load(myDataset.CrystalFilePath)
                .SetDataSource(myDataset.Dados)
                .PrintOptions.ApplyPageMargins(myDataset.Margens)
                If myDataset.NoLogo = True Then
                    Call UpdateReportObjectProperties(myCR, strFldLogotipo, 0, 0, 0, 0, False)
                    Call UpdateReportObjectProperties(myCR, strFldxNome, 0, 120, 0, 3480)
                    Call UpdateReportObjectProperties(myCR, strFldxEndereco, 0, 120, 0, 0)
                End If
                If PrinterName.Trim <> "{ConfigNotFound}" And PrinterName.Trim <> String.Empty Then
                    .PrintOptions.PrinterName = PrinterName
                End If
                .PrintToPrinter(1, False, 0, 0)
            End With
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Sub
    ''' <summary>
    ''' Salva o relatório em PDF automaticamente (FUNCIONAL MAIS OU MENOS)
    ''' </summary>
    Private Sub SendByMail(ByVal strFileName As String)
        'Try
        '    Dim mail As New CrystalDecisions.Shared.MicrosoftMailDestinationOptions
        '    Dim exOptions As New CrystalDecisions.Shared.ExportOptions
        '    Dim myDataset As New angDANFE

        '    myDataset.LoadConfig()
        '    myDataset.FileName = strFileName


        '    'TODO: AINDA EM ESTES (trocar pela nova rotina dinamica de seleção de DANFE se necessário)
        '    Dim CrReport As New relDanfeMod1() ' Report Name
        '    Dim CrExportOptions As New CrystalDecisions.Shared.ExportOptions
        '    Dim CrMailDestinationOptions As New CrystalDecisions.Shared.MicrosoftMailDestinationOptions()
        '    Dim CrFormatTypeOptions As New CrystalDecisions.Shared.PdfRtfWordFormatOptions()

        '    '-- opções do email
        '    CrMailDestinationOptions.MailToList = "bredrick.sa@gmail.com"
        '    CrMailDestinationOptions.MailCCList = ""
        '    CrMailDestinationOptions.MailSubject = "teste do VB.net"
        '    CrMailDestinationOptions.MailMessage = "djafh laksjdhflkajsdhfl kjsdh f"
        '    'CrMailDestinationOptions.UserName = ""
        '    'CrMailDestinationOptions.Password = ""

        '    CrExportOptions = CrReport.ExportOptions

        '    With CrExportOptions
        '        'Set the destination
        '        .ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.MicrosoftMail
        '        'Set the format to PDF
        '        .ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat
        '        'Set the destination options 
        '        .DestinationOptions = CrMailDestinationOptions
        '        .FormatOptions = CrFormatTypeOptions
        '    End With
        '    CrReport.SetDataSource(myDataset.Dados)
        '    CrReport.Export()

        'Catch ex As Exception
        '    Call MsgBox(ex.Message)
        'End Try
    End Sub
    ''' <summary>
    ''' Altera confirgurações do campos do relatório
    ''' </summary>
    ''' <param name="myReportDocument">Nome do Socumento = ReportDocument</param>
    ''' <param name="reportObjectName">Nome do Objeto a ser alterado</param>
    ''' <param name="top">Margem superior</param>
    ''' <param name="left">Margem esquerda</param>
    ''' <param name="height">Altura do objeto</param>
    ''' <param name="width">Largura do objeto</param>
    ''' <param name="Visible">Define se visível o não</param>
    ''' <remarks></remarks>
    Private Sub UpdateReportObjectProperties(ByVal myReportDocument As ReportDocument, _
                                             ByVal reportObjectName As String, _
                                             ByVal top As Integer, _
                                             ByVal left As Integer, _
                                             ByVal height As Integer, _
                                             ByVal width As Integer, _
                                             Optional ByVal Visible As Boolean = True)
        Try
            Dim myReportObject As ReportObject = myReportDocument.ReportDefinition.ReportObjects.Item(reportObjectName)
            If Not myReportObject Is Nothing Then
                With myReportObject
                    If top > 0 Then
                        .Top = top
                    End If
                    If left > 0 Then
                        .Left = left
                    End If
                    If height > 0 Then
                        .Height = height
                    End If
                    If width > 0 Then
                        .Width = width
                    End If
                    If Visible = False Then
                        .Height = 0
                        .Width = 0
                    End If
                End With

                'Dim myBorder As Border = myReportObject.Border()
                'myBorder.BackgroundColor = Color.White
                'myBorder.BorderColor = Color.Red

                'Dim myObjectFormat As ObjectFormat = myReportObject.ObjectFormat
                'myObjectFormat.EnableCanGrow = False
                'myObjectFormat.EnableSuppress = False
                'myObjectFormat.EnableCloseAtPageBreak = True
                'myObjectFormat.EnableKeepTogether = True
            End If
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Sub
End Class
